package com.vstyran.radio.managers
{
	import com.vstyran.radio.consts.PostingType;
	import com.vstyran.radio.events.MetaEvent;
	import com.vstyran.radio.vos.MusicChunk;
	import com.vstyran.radio.vos.Track;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SampleDataEvent;
	import flash.filesystem.File;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundLoaderContext;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;

	public class ServerManager
	{
		public function ServerManager()
		{
			radioManager = new RadioManager();
			radioManager.publisher = true;
			radioManager.initConnection();
			
			metaManager.addEventListener("metaReceived", metaReceiveHandler);
			
			sound = new Sound();
			sound.addEventListener(SampleDataEvent.SAMPLE_DATA, sampleDataReceiver);
			
			
		}
		
		[Bindable]
		public var playList:ArrayCollection = new ArrayCollection();
		
		[Bindable]
		public var radioManager:RadioManager;
		
		private var chanel:SoundChannel;
		
		private var sound:Sound;
		private var soundSource:Sound;
		
		[Bindable]
		public var currentSong:Track;
		
		private var _volume:Number = 1;
		
		[Bindable]
		public function get volume():Number
		{
			return _volume;
		}
		
		public function set volume(value:Number):void
		{
			_volume = value;
			
			if(chanel)
				chanel.soundTransform = new SoundTransform(_volume);
		}
		
		public function broadcast():void
		{
			broadcastTrack(getNextSong());
		}
		
		public function broadcastTrack(track:Track):void
		{
			if(!track)
				return;
			
			if(chanel)
			{
				chanel.stop();
				chanel = null;
			}
			
			if(track.isURL)
			{
				soundSource = new Sound();
				soundSource.addEventListener(ProgressEvent.PROGRESS, progressHandler);
				soundSource.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
				soundSource.load(new URLRequest(track.path));
			}
			else
			{
				soundSource = new Sound();
				soundSource.addEventListener(Event.COMPLETE, loadedHandler);
				soundSource.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
				soundSource.load(new URLRequest(track.path));
			}
			currentSong = track;
		}
		
		private function getNextSong():Track
		{
			if(playList.length > 0)
				if(!currentSong)
				{
					currentSong = playList.getItemAt(0) as Track;
				}
				else
				{
					var index:int = playList.getItemIndex(currentSong);
					if(index == -1 || index > playList.length-2)
					{
						currentSong = playList.getItemAt(0) as Track;
					}
					else
					{
						currentSong = playList.getItemAt(index+1) as Track;
					}
				}
			return currentSong;
		}
		
		protected function sampleDataReceiver(event:SampleDataEvent):void
		{
			var bytes:ByteArray = new ByteArray();
			soundSource.extract(bytes, 4096);
			if(bytes.length > 0)
			{
				var rating:Number = Math.ceil((currentSong.numLike*2/(currentSong.numLike*2 + currentSong.numUnLike*2 + radioManager.numConnections - (currentSong.numLike + currentSong.numUnLike)))*100)/10;
				
				event.data.writeBytes(bytes);
				radioManager.post(new MusicChunk(metaManager.peerId, rating, currentSong.name, new Date().getTime(), bytes));
			}
		}
		
		protected function loadedHandler(event:Event):void
		{
			chanel = sound.play();
			chanel.soundTransform = new SoundTransform(_volume);
			chanel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
		}
		
		protected function errorHandler(event:Event):void
		{
			Alert.show("Cant load");
		}
		
		protected function soundCompleteHandler(event:Event):void
		{
			broadcast();
		}
		
		protected function progressHandler(event:ProgressEvent):void
		{
			if(event.bytesLoaded > 32000 && !chanel)
			{
				chanel = sound.play();
				chanel.soundTransform = new SoundTransform(_volume);
				chanel.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
			}
		}
		
		public var metaManager:MetaManager = new MetaManager();
		
		protected function metaReceiveHandler(event:MetaEvent):void
		{
			currentSong.addRating(event.meta);
		}
	}	
}